﻿using System;
using System.Web;
using System.Net;

namespace WebServer.Service.BLL
{
    /// <summary>
    /// 网站承载对象
    /// </summary>
    public class WebHost : MarshalByRefObject
    {
        #region "字段"

        /// <summary>
        /// http监听程序
        /// </summary>
        private HttpListener listener;

        #endregion

        #region "公共方法"

        /// <summary>
        /// 初始化程序域
        /// </summary>
        /// <param name="listenPrefix">监听的前缀</param>
        public void Initial(String[] listenPrefix)
        {
            InitialHttpListener(listenPrefix);
        }

        /// <summary>
        /// 程序域开始处理请求
        /// </summary>
        public void Start()
        {
            this.listener.Start();
            this.listener.BeginGetContext(HttpRequestCallBack, this.listener);
        }

        /// <summary>
        /// 程序域生命期最长（无限长）
        /// </summary>
        /// <returns></returns>
        public override Object InitializeLifetimeService()
        {
            return null;
        }

        #endregion

        #region "私有方法"

        /// <summary>
        /// http请求回调的方法
        /// </summary>
        /// <param name="result"></param>
        private void HttpRequestCallBack(IAsyncResult result)
        {
            HttpListener listener = result.AsyncState as HttpListener;
            if (listener != null)
            {
                try
                {
                    HttpListenerContext context = listener.EndGetContext(result);
                    Action<HttpListenerContext> a = new Action<HttpListenerContext>((c) =>
                    {
                        HttpRuntime.ProcessRequest(new WebRequest(c));
                    });
                    a.BeginInvoke(context, null, null);
                }
                catch (Exception)
                { }
                listener.BeginGetContext(HttpRequestCallBack, listener);
            }
        }

        /// <summary>
        /// 初始化http监听程序
        /// </summary>
        /// <param name="listenPrefix">监听前缀</param>
        private void InitialHttpListener(String[] listenPrefix)
        {
            this.listener = new HttpListener();
            //添加用户配置的监听url前缀
            if (listenPrefix != null)
            {
                for (Int32 i = 0; i < listenPrefix.Length; i++)
                {
                    if (!this.listener.Prefixes.Contains(listenPrefix[i]))
                        this.listener.Prefixes.Add(listenPrefix[i]);
                }
            }
        }

        #endregion
    }
}
